package com.bang.study.query;

import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

/**
 * @ClassName: GrandParentChildQuery
 * @author: BANG
 * @Date: 2020/01/16 15:08
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /company/country/_search
 * {
 *   "query": {
 *     "has_child": {
 *       "type": "rd_center",
 *       "query": {
 *         "has_child": {
 *           "type": "employee",
 *           "query": {
 *             "match": {
 *               "hobby": "爬山"
 *             }
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 */
public class GrandParentChildQuery {

    public static void main(String[] args) throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("company").setTypes("country")
                .setQuery(
                        QueryBuilders.hasChildQuery("rd_center",
                                QueryBuilders.hasChildQuery("employee", QueryBuilders.matchQuery("hobby", "爬山"), ScoreMode.None)
                                , ScoreMode.None))
                .get();
        for (SearchHit searchHit : searchResponse.getHits().getHits()) {
            System.err.println(searchHit.getSourceAsString());
        }

        client.close();

    }
}
